package com.MutiModule.common.utils.webservice.http;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.wsdl.Definition;
import javax.wsdl.WSDLException;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

import com.MutiModule.common.utils.JSONUtilss;
import com.MutiModule.common.utils.XmlParserUtilss;

public class HttpWebServiceMain {

	private String namespace;  
    private String methodName;  
    private String wsdlLocation;  
    private String soapResponseData;  
  
    //构造函数  
    public HttpWebServiceMain(String namespace, String methodName,  
            String wsdlLocation) {  
  
        this.namespace = namespace;  
        this.methodName = methodName;  
        this.wsdlLocation = wsdlLocation;  
    }  
  
    //通过invoke函数创建  执行postmethod  
    private int invoke(Map<String, String> patameterMap) throws Exception {  
        //创建ｐｏｓｔ方法  
        PostMethod postMethod = new PostMethod(wsdlLocation);  
         
        //建立soap请求数据  
        String soapRequestData = buildRequestData(patameterMap);  
          
        // 然后把Soap请求数据添加到PostMethod中  
        byte[] bytes = soapRequestData.getBytes("utf-8");  
        InputStream inputStream = new ByteArrayInputStream(bytes, 0, bytes.length);  
        RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,  
                bytes.length, "application/soap+xml; charset=utf-8");  
        postMethod.setRequestEntity(requestEntity);  
          
        //创建httpclient客户端，执行post方法  
        HttpClient httpClient = new HttpClient();  
        int statusCode = httpClient.executeMethod(postMethod);  
        soapResponseData = postMethod.getResponseBodyAsString();  
        
        return statusCode;  
    }  
  
    //通过buildRequestData函数来创建soap请求  
    private String buildRequestData(Map<String, String> patameterMap) {  
        StringBuffer soapRequestData = new StringBuffer();  
        soapRequestData.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");  
        soapRequestData  
                .append("<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""  
                        + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""  
                        + " xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">");  
        soapRequestData.append("<soap12:Body>");  
        soapRequestData.append("<" + methodName + " xmlns=\"" + namespace  
                + "\">");  
  
        Set<String> nameSet = patameterMap.keySet();  
        for (String name : nameSet) {  
            soapRequestData.append("<" + name + ">" + patameterMap.get(name)  
                    + "</" + name + ">");  
        }  
          
        soapRequestData.append("</" + methodName + ">");  
        soapRequestData.append("</soap12:Body>");  
        soapRequestData.append("</soap12:Envelope>");  
  
        return soapRequestData.toString();  
    }  
    
    private static SOAPMessage formatSoapString(String soapString) {
    	try {
			MessageFactory msgFactory = MessageFactory.newInstance();
			try {
				SOAPMessage reqMsg = msgFactory.createMessage(new MimeHeaders(), new ByteArrayInputStream(soapString.getBytes("UTF-8")));
				reqMsg.saveChanges();
				return reqMsg;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return null;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
			
		} catch (SOAPException e) {
			e.printStackTrace();
			return null;
		}
    }
    
    public static String output(String wsdlLocation, String methodName, String inputJsonStr) {
    	String outPutStr = null;
		// 获取命名空间
		try {
			WSDLFactory factory = WSDLFactory.newInstance();
			WSDLReader reader = factory.newWSDLReader();
			Definition def = reader.readWSDL(wsdlLocation);
			String targetNamespace = def.getTargetNamespace();

			HttpWebServiceMain _operator = new HttpWebServiceMain(targetNamespace, methodName, wsdlLocation);
			
			Map<String, String> patameterMap = JSONUtilss.readValue(inputJsonStr, HashMap.class);
			
			try {
				int statusCode = _operator.invoke(patameterMap);
				if(statusCode == 200) {  
					String bodyStr = XmlParserUtilss.getBodyNodeByXMLStr(_operator.soapResponseData, "Body");
					outPutStr = bodyStr;
					return outPutStr;
				}  
				else {  
					System.out.println("调用失败！错误码：" + statusCode); 
					return outPutStr;
				}  
			} catch (Exception e) {
				e.printStackTrace();
				return outPutStr;
			}  

		} catch (WSDLException e) {
			e.printStackTrace();
			return outPutStr;
		}
	}
  
}
